#!/usr/bin/env python
#-*-coding:utf-8-*-



import tornado.ioloop
import tornado.web
import predict

import json
import argparse
import os
model = None

class PhoneClassHandler(tornado.web.RequestHandler):

    def post(self):
        data = json.loads(self.request.body)
        text = data.get("text")
        if not text:
            self.write({"labels":[], "prob":[]})
            return
        print(text)
        labels, probs  = model.predict(text)
        labels = [int(i) for i in labels]
        probs = [float(prob) for prob in probs]
        result = {"labels": list(labels), "probs": probs}
        self.write(json.dumps(result))


def make_app():
    return tornado.web.Application([
        (r"/", PhoneClassHandler),
    ], debug=True)


if __name__ == "__main__":

    parser = argparse.ArgumentParser(description='the server of model')

    parser.add_argument('--port',  type=int, help='the port of server')
    parser.add_argument('--checkpoint_dir',  help='path of checkpoints')


    args = parser.parse_args()
    model_path = args.checkpoint_dir
    port = args.port

    if not  os.path.exists(model_path):
        print("model path '%s' is not exists"%(model_path))
        exit(0)

    model = predict.CnnModel(model_path)
    app = make_app()
    app.listen(port)
    print("server start at %d"%(port,))
    tornado.ioloop.IOLoop.current().start()